package msg

import (
	"fmt"
	"github.com/satori/go.uuid"
	"talent.com/agency_im/common/user"
	"talent.com/server/durotar.git/log"
)

// 发送消息，可能是客户端发起或者服务端发起
func SaveMessage(message *Message) error {
	if message.ClientID == "" && !message.SendSelf { // 如果是服务端发送消息，则补全ClientID
		message.ClientID = fmt.Sprintf("%v", uuid.NewV1())
	}

	if newMsg, err := InsertMessage(message); err != nil {
		return err
	} else {
		var (
			source *user.User
			target *user.User
			err    error
		)
		if source, err = user.GetUser(newMsg.SourceID); err != nil {
			return err
		}

		if target, err = user.GetUser(newMsg.TargetID); err != nil {
			return err
		}
		UpdateTopicMaxMsgIDAndIsReplied(&MessageTopic{
			UserPlatformID:   source.PlatformID,
			UserID:           newMsg.SourceID,
			TargetPlatformID: target.PlatformID,
			TargetID:         newMsg.TargetID,
			TopicID:          newMsg.TopicID,
			MaxMsgID:         newMsg.ID,
			TopicType:        newMsg.TopicType,
			IsReplied:        true,
		})

		UpdateTopicMaxMsgIDAndIsReplied(&MessageTopic{
			UserPlatformID:   target.PlatformID,
			UserID:           newMsg.TargetID,
			TargetPlatformID: source.PlatformID,
			TargetID:         newMsg.SourceID,
			TopicID:          newMsg.TopicID,
			MaxMsgID:         newMsg.ID,
			TopicType:        newMsg.TopicType,
			IsReplied:        false,
		})
		return nil
	}
}

func GetUnNotifiedMessagesByTopicID(topicID string, msgs *map[uint64][]Message) error {
	topics, err := GetUnreadTopicsByTopicID(topicID)
	if err != nil {
		return err
	}

	for _, tp := range topics {
		if tp.MaxMsgID == tp.ReadMsgID {
			continue
		} else {
			messages, err := FetchOldestMessagesInTopic(topicID, tp.ReadMsgID, 100)
			if err != nil {
				log.Error("notify messages for topicID: %v , error : %v", topicID, err)
				continue
			} else {
				(*msgs)[tp.UserID] = messages
			}
		}
	}
	return nil
}

func GetUnNotifiedMessagesByUserID(userID uint64, msgs *map[string][]Message) error {
	topics, err := GetUnreadTopicsByUserID(userID)
	if err != nil {
		return err
	}

	for _, tp := range topics {
		if tp.MaxMsgID == tp.ReadMsgID {
			continue
		} else {
			messages, err := FetchOldestMessagesInTopic(tp.TopicID, tp.ReadMsgID, 100)
			if err != nil {
				log.Error("notify message for error for topicID: %v , error : %v", tp.TopicID, err)
				continue
			} else {
				(*msgs)[tp.TopicID] = messages
			}
		}
	}
	return nil
}
